<script setup lang="ts">
import { reactive, onMounted } from 'vue'
import { ElMessageBox } from 'element-plus'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { Edit, Delete } from '@element-plus/icons-vue'
import { getGroups, deleteGroup, getUserPageAuth } from '@/api/system/authority'
import { useEmitt } from '@/hooks/web/useEmitt'
import { hasElementAuth } from '@/utils/authority'
import { useCache } from '@/hooks/web/useCache'
import { saveGroup } from '@/api/system/authority'
import { getCurUser } from '@/utils'
import { useI18n } from '@/hooks/web/useI18n'
import { useLocaleStore } from '@/store/modules/locale'
defineOptions({
  name: 'GroupList'
})

const { t } = useI18n()
const { push, currentRoute } = useRouter()
const { wsCache } = useCache()
const localeStore = useLocaleStore()
//当前语言
const curLang = localeStore.getCurrentLocale.lang
const state = reactive({
  //查询参数
  queryParams: {
    Q_group_name_S_LK: ''
  },
  // 表格數據
  viewTable: [{}],
  enable: '1',
  disable: false,
  // 分頁相關屬性
  currentPage: 1,
  nameField: 'groupName',
  pageSize: 2000,
  totalCount: 0,
  pageAuths: [{}]
})
onMounted(async () => {
  if (curLang == 'en') {
    state.nameField = 'enName'
  } else if (curLang == 'zh_HK') {
    state.nameField = 'hkName'
  }
  search()
  let muid = currentRoute.value.meta.id //wsCache.get('memuId')

  state.pageAuths = (await getUserPageAuth(muid)).data
})

// 角色授权
const authorize = (row: object) => {
  wsCache.set('curGroup', row)
  push({ name: 'Authorization' })
}
// 新增
const insert = () => {
  wsCache.set('curGroup', null)
  push({ name: 'GroupAdd' })
}
// 修改
const edit = (row: object) => {
  wsCache.set('curGroup', row)
  push({ name: 'GroupAdd' })
}

//删除
const del = (groupId) => {
  ElMessageBox.confirm(t('module.delMsg'), t('common.warning'), {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  })
    .then(async () => {
      await deleteGroup(groupId).then((res) => {
        const result = res as any
        ElMessageBox.alert(t(result.message))
        if (result.success) {
          search()
        }
      })
    })
    .catch(() => {})
}

/**
 * @description  定义列表刷新事件
 * @author Elwin ZHANG
 * @date 2022-06-08 11:44
 */
useEmitt({
  //刷新列表事件
  name: 'refreshList',
  callback: (type: string) => {
    if (type === 'add') {
      state.currentPage = 1
    }
    search()
  }
})
//修改状态
const updateGroupStatus = async (rowData) => {
  let userDate = getCurUser()
  let params = rowData
  params.tenantId = userDate.tenantId
  params.updateBy = userDate.username
  await saveGroup(params).then((res) => {
    const result = res as any
    ElMessage.success(t(result.message))
  })
}
// updateGroupStatus
//查询列表数据
const search = async () => {
  state.viewTable = []
  await getGroups({
    pageNo: state.currentPage,
    pageSize: state.pageSize,
    params: state.queryParams,
    sortField: 'g.sort',
    sortOrder: 'asc'
  })
    .then((res) => {
      const result = res as any
      var data = genGroupTypeName(result.result.data)
      //取一级节点，生成树形结构
      for (const rowAny of data) {
        const row = rowAny as any
        if (row.level == 1) {
          state.viewTable.push(row)
          //递归处理各一级节点
          convertData(row, data)
        }
      }
    })
    .catch(() => {})
}

/**
 * @description 生成某节点的所有子节点，为了显示树形表格
 * @param parent 父节点
 * @author Elwin ZHANG
 * @date 2023-04-07 13:15
 */
const convertData = (parent: any, data: []) => {
  for (const rowAny of data) {
    const row = rowAny as any
    if (row.parentId == parent.groupId) {
      if (!parent.children) {
        parent.children = []
      }
      parent.children.push(row)
      //递归处理子节点
      convertData(row, data)
    }
  }
}
/**
 *根据当前语言生成组类型名称
 */
const genGroupTypeName = (data) => {
  if (data == null) {
    return null
  }
  for (var row of data) {
    row.groupTypeName = t('group.groupType' + row.groupType)
  }
  return data
}
</script>
<template>
  <!-- 搜索列表卡片 -->
  <el-card>
    <!-- 表頭按鈕 -->
    <el-row id="topBtnRight">
      <el-button
        type="success"
        size="small"
        plain
        @click="insert"
        v-if="hasElementAuth(state.pageAuths, 'add')"
      >
        <Icon icon="material-symbols:add-circle-rounded" /><span>{{ $t('common.add') }}</span>
      </el-button>
      <el-button type="info" size="small" plain @click="search">
        <Icon icon="tabler:refresh" /><span>{{ $t('common.refresh') }}</span></el-button
      >
    </el-row>
    <!-- 搜索結果表格 -->
    <el-table
      :data="state.viewTable"
      row-key="groupId"
      default-expand-all
      style="width: 100%"
      tooltip-effect="light"
      stripe
      :header-cell-style="{
        background: 'var(--el-color-primary-light-9)',
        color: '#409eff'
      }"
    >
      <el-table-column type="index" min-width="60">
        <template #header>
          <div style="margin-bottom: -10px">
            <Icon icon="ant-design:field-number-outlined" size="24" :title="$t('common.number')"
          /></div>
        </template>
      </el-table-column>
      <el-table-column
        :prop="state.nameField"
        :label="$t('group.groupName')"
        show-overflow-tooltip
        min-width="130"
      />
      <el-table-column
        prop="groupTypeName"
        :label="$t('group.groupType')"
        show-overflow-tooltip
        min-width="90"
      />
      <el-table-column
        prop="level"
        :label="$t('menu.level')"
        show-overflow-tooltip
        min-width="90"
        align="center"
      />
      <el-table-column prop="sort" :label="$t('common.sort')" min-width="90" />
      <el-table-column prop="status" :label="$t('common.status')" min-width="90">
        <template #default="{ row }">
          <el-switch
            @change="updateGroupStatus(row)"
            v-model.number="row.status"
            :active-value="1"
            :inactive-value="0"
          />
        </template>
      </el-table-column>

      <el-table-column fixed="right" :label="$t('common.operation')" width="130">
        <template #default="{ row }">
          <el-button
            type="primary"
            size="small"
            plain
            circle
            :title="$t('common.modify')"
            @click="edit(row)"
            v-if="hasElementAuth(state.pageAuths, 'edit')"
          >
            <el-icon>
              <Edit />
            </el-icon>
          </el-button>
          <el-button
            type="danger"
            size="small"
            plain
            circle
            :title="$t('common.delete')"
            @click="del(row.groupId)"
            v-if="hasElementAuth(state.pageAuths, 'delete') && !row.children"
          >
            <el-icon>
              <Delete />
            </el-icon>
          </el-button>
          <el-button
            type="success"
            size="small"
            :title="$t('group.authorize')"
            plain
            circle
            @click="authorize(row)"
            v-if="hasElementAuth(state.pageAuths, 'authorize')"
          >
            <Icon icon="openmoji:authority"
          /></el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>
<style lang="less" scoped>
.el-table {
  font-size: 12px;
}
//搜索條樣式
.input-with-select {
  width: 50%;
  margin-left: auto;
  margin-right: auto;
}

:deep(.el-input-group__append) {
  background-color: #ecf5ff;
  border-color: #a0cfff;
  color: #409eff;
  box-shadow: #409eff;
  cursor: pointer;
}

:deep(.el-input-group__append):hover {
  background-color: #ecf5ff;
  border-color: #409eff !important;
  color: #409eff;
  box-shadow: #409eff;
  cursor: pointer;
}

.el-col {
  /* padding: 0; */
  line-height: 56px;

  .radioOne {
    position: relative;
    left: 5px;
  }

  .radioTwo {
    position: relative;
    left: -27px;
  }

  p {
    margin-left: 5px;
    text-align: left;
    font-size: 12px;
    position: relative;
    bottom: -10px;
  }

  .remark {
    font-size: 12px;
    color: #6e6e6e;
    padding-left: 5px;
  }
}

.demo-pagination-block {
  display: flex;
  justify-content: center;
  justify-items: center;
  margin-top: 20px;
  margin-bottom: 20px;
}
</style>
